import db from '../config/database.js'

// 解析展览数据中的 JSON 字段
function parseExhibitionData(exhibition) {
  if (!exhibition) return null

  return {
    ...exhibition,
    image_url: exhibition.image_url ? JSON.parse(exhibition.image_url) : [],
    highlights: exhibition.highlights ? JSON.parse(exhibition.highlights) : [],
    notices: exhibition.notices ? JSON.parse(exhibition.notices) : []
  }
}

// 获取展览列表
export async function getExhibitions(req, res) {
  try {
    const {status} = req.query

    let query = 'SELECT * FROM exhibitions'
    const params = []

    if (status) {
      query += ' WHERE status = ?'
      params.push(status)
    }

    query += ' ORDER BY start_date DESC'

    const [exhibitions] = await db.query(query, params)

    // 解析 JSON 字段
    const parsedExhibitions = exhibitions.map(parseExhibitionData)

    res.json({
      success: true,
      data: parsedExhibitions
    })
  } catch (error) {
    console.error('获取展览列表错误:', error)
    res.status(500).json({
      success: false,
      error: '获取展览列表失败'
    })
  }
}

// 获取展览详情
export async function getExhibition(req, res) {
  try {
    const {id} = req.params

    const [exhibitions] = await db.query('SELECT * FROM exhibitions WHERE id = ?', [id])

    if (exhibitions.length === 0) {
      return res.status(404).json({
        success: false,
        error: '展览不存在'
      })
    }

    // 解析 JSON 字段
    const exhibition = parseExhibitionData(exhibitions[0])

    res.json({
      success: true,
      data: exhibition
    })
  } catch (error) {
    console.error('获取展览详情错误:', error)
    res.status(500).json({
      success: false,
      error: '获取展览详情失败'
    })
  }
}

// 获取票种列表
export async function getTicketTypes(req, res) {
  try {
    const {exhibitionId} = req.params

    const [ticketTypes] = await db.query(
      'SELECT * FROM ticket_types WHERE exhibition_id = ? ORDER BY price ASC',
      [exhibitionId]
    )

    // 为每个票种计算已售数量和剩余数量
    const ticketTypesWithStock = await Promise.all(
      ticketTypes.map(async (ticketType) => {
        // 查询已售数量（包括待支付和已支付的订单）
        const [soldResult] = await db.query(
          `SELECT COALESCE(SUM(oi.quantity), 0) as sold 
           FROM order_items oi 
           JOIN orders o ON oi.order_id = o.id 
           WHERE oi.ticket_type_id = ? AND o.status IN ('pending', 'paid')`,
          [ticketType.id]
        )

        const sold = soldResult[0].sold
        const stock = ticketType.stock
        
        // 计算剩余数量（stock = -1 表示无限库存）
        const available = stock === -1 ? -1 : stock - sold
        const isSoldOut = stock !== -1 && available <= 0

        return {
          ...ticketType,
          sold,           // 已售数量
          available,      // 剩余数量（-1 表示无限）
          is_sold_out: isSoldOut  // 是否售罄
        }
      })
    )

    res.json({
      success: true,
      data: ticketTypesWithStock
    })
  } catch (error) {
    console.error('获取票种列表错误:', error)
    res.status(500).json({
      success: false,
      error: '获取票种列表失败'
    })
  }
}
